package com.matt.repository.impl;

import com.matt.foundation.DO.ClassListDO;
import com.matt.foundation.DO.TeacherDO;
import com.matt.foundation.constant.PermissionConstant;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.foundation.query.ClassesQuery;
import com.matt.foundation.utils.CollectionUtil;
import com.matt.foundation.vo.WebClassesPageVo;
import com.matt.repository.base.BaseNativeSqlRepository;
import com.matt.repository.base.ClassesTeacherRepository;
import com.matt.repository.rel.RelClassesTeacherRepository;
import com.matt.service.remoteCall.SsoCallService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * *******************************
 * Created by Ron.
 * form com.matt
 * on 2017/7/11
 * *******************************
 */
@Service
public class ClassesTeacherRepositoryImpl extends BaseNativeSqlRepository implements ClassesTeacherRepository {

    @Autowired
    private SsoCallService ssoCallService;

    @Autowired
    private RelClassesTeacherRepository relClassesTeacherRepository;

    @Override
    public List<Object[]> findByUserAndArea(String staffId, String areaId) {
        String findTeacherSql=String.format("select c.id as id, c.name as name, c.baseTime as baseTime, (SELECT COUNT(rc.childrenId) from rel_classes_children rc where c.id = rc.classesId) AS studentNum, c.remark as remark , c.limitNum as limitNum " +
                 " from rel_classes_teacher rel left join  classes c on c.id = rel.classesId where rel.staffId = '%s' and c.areaId='%s'", staffId, areaId);
        List<Object[]> objectArrayList = sqlArrayList(findTeacherSql);
        return objectArrayList;
    }

    @Override
    public List<ClassListDO> findClassesByTeacher(String staffId, String areaId) {
//        private String inChargeTeacherName;
//        private String inChargeTeacherId;
        String findTeacherSql = "select c.id as id, c.name as name, c.category as category, c.inChargeTeacherName as inChargeTeacherName, " +
                " c.inChargeTeacherId as inChargeTeacherId " +
                " from rel_classes_teacher rel left join  classes c on c.id = rel.classesId " +
                " where (rel.staffId = :1 or c.`inChargeTeacherId`= :2) and c.areaId=:3 and c.deleted=false GROUP BY c.id";

        List params = new ArrayList();
        params.add(staffId);
        params.add(staffId);
        params.add(areaId);

        List<ClassListDO> objectArrayList = sqlObjectList(findTeacherSql, params, ClassListDO.class);
        return objectArrayList;
    }

    @Override
    public List<ClassListDO> findClassesByDoctor(String staffId, String areaId) {
        String findTeacherSql=String.format("select c.id as id, c.name as name, c.category as category, c.inChargeTeacherName as inChargeTeacherName, c.inChargeTeacherId as inChargeTeacherId " +
                " from rel_classes_doctor rel left join  classes c on c.id = rel.classesId where rel.staffId = '%s' and c.areaId='%s' and c.deleted=false ", staffId, areaId);
        List<ClassListDO> objectArrayList = sqlObjectList(findTeacherSql, ClassListDO.class);
        return objectArrayList;
    }

    @Override
    public List<ClassListDO> findClassesByAreaLeader(String staffId, String areaId){
        String findTeacherSql=String.format("select c.id as id, c.name as name, c.category as category, c.inChargeTeacherName as inChargeTeacherName, c.inChargeTeacherId as inChargeTeacherId " +
                " from  classes c   where  c.areaId='%s' and c.deleted = false ", areaId);
        List<ClassListDO> objectArrayList = sqlObjectList(findTeacherSql, ClassListDO.class);
        return objectArrayList;
    }

    @Override
    public List<TeacherDO> findByClassesId(String classesId) {
//        String findTeacherSql=String.format("select u.id AS id , u.realName AS name ,u.headImgUrl AS imgUrl"
//                + " FROM staff u LEFT join rel_classes_teacher rel on rel.staffId = u.id where rel.classesId='%s'", classesId);
        List<String> staffIds = relClassesTeacherRepository.findByClassesId(classesId).stream().map(o->o.getStaffId()).collect(Collectors.toList());
        String[] ids = CollectionUtil.toArray(staffIds);
        List<StaffDTO> staffDTOList = ssoCallService.getStaffDTOList(null, ids);
        List<TeacherDO> teacherDOList = staffDTOList.stream().map(o->TeacherDO.of(o)).collect(Collectors.toList());
        return teacherDOList;
    }

    @Override
    public List<WebClassesPageVo> findClassesByCondition(String roleCode, ClassesQuery query) {
        String querySql = String.format("select c.id as id, c.name as name, c.baseTime as baseTime, (SELECT count(rc.childrenId) from rel_classes_children rc where c.id = rc.classesId) AS studentNum, " +
                " c.remark as remark, c.limitNum as limitNum, c.created as created, c.inChargeTeacherName as inChargeTeacherName, c.beginMonth as beginMonth, c.endMonth as endMonth, c.category as category,c.deleted as deleted " +
                " from classes c " +
                (PermissionConstant.Role.DOCTOR.codeOf().equals(roleCode) && StringUtils.isNotBlank(query.getStaffId())
                        ? (" left join rel_classes_doctor dr on c.id = dr.classesId ")
                        :"") +
                (PermissionConstant.Role.TEACHER.codeOf().equals(roleCode) && StringUtils.isNotBlank(query.getStaffId())
                        ? ("left join rel_classes_teacher rel on c.id = rel.classesId ")
                        :"") +
                " where ", query.getDate(), query.getDate());

        String condition = "";
        if (StringUtils.isNotBlank(query.getAreaId())) {
            condition += String.format("and c.areaId = '%s' ", query.getAreaId());
        }
        if (StringUtils.isNotBlank(query.getId())) {
            condition += String.format("and c.id = '%s' ", query.getId());
        }
        if (StringUtils.isNotBlank(query.getStaffId())){
            if(PermissionConstant.Role.DOCTOR.codeOf().equals(roleCode)) {
                condition += String.format("and dr.staffId = '%s' ", query.getStaffId());
            }else if(PermissionConstant.Role.GARDEN_LEADER.codeOf().equals(roleCode) || PermissionConstant.Role.EXECUTE_LEADER.codeOf().equals(roleCode)){

            }else{
                condition += String.format("and rel.staffId = '%s' ", query.getStaffId());
            }
        }

        if (StringUtils.isNotBlank(query.getName())){
            condition += String.format("and c.name like concat('%s', '%s', '%s') ", "%", query.getName(), "%");
        }

        if (Objects.nonNull(query.getStatus())){
            condition += String.format("and c.deleted = false ");
        }

        if(condition.startsWith("and")){
            condition = condition.substring(3);
        }
        querySql += condition;

        querySql += " group by c.id order by c.deleted asc, c.category asc, c.created desc " ;
        querySql += String.format(" limit %s, %s ", query.getPageNum() * query.getPageSize() ,  query.getPageSize());
        List<WebClassesPageVo> list = sqlObjectList(querySql, WebClassesPageVo.class);
        return list;
    }

    @Override
    public Long countClassesByArea(ClassesQuery query) {
        String querySql = String.format("SELECT count(c.id) " +
                " from classes c where true");

        if (StringUtils.isNotBlank(query.getAreaId())) {
            querySql += String.format(" and c.areaId = '%s' ", query.getAreaId());
        }

        if (StringUtils.isNotBlank(query.getName())){
            querySql += String.format(" and c.name like concat('%s', '%s', '%s') ", "%", query.getName(), "%");
        }
        if (Objects.nonNull(query.getStatus())){
            querySql += String.format(" and c.deleted = false ");
        }

        List objectArrayList = sqlSingleList(querySql);
        return Long.valueOf(objectArrayList.get(0).toString());
    }

    @Override
    public Long countClassesByStaff(String roleCode, ClassesQuery query) {
    	
        String querySql = String.format("select count(*) from(select c.id  from classes c " +
                (!PermissionConstant.Role.GARDEN_LEADER.codeOf().equals(roleCode)
                        ? ("left join rel_classes_teacher rel on c.id = rel.classesId left join rel_classes_doctor dr on c.id = dr.classesId ")
                        :"") +
                "where true");

        if (StringUtils.isNotBlank(query.getStaffId())){
            if(PermissionConstant.Role.DOCTOR.codeOf().equals(roleCode)) {
                querySql += String.format(" and dr.staffId = '%s' ", query.getStaffId());
            }else if(PermissionConstant.Role.GARDEN_LEADER.codeOf().equals(roleCode) || PermissionConstant.Role.EXECUTE_LEADER.codeOf().equals(roleCode)){

            }else{
                querySql += String.format(" and rel.staffId = '%s' ", query.getStaffId());
            }
        }
        if (StringUtils.isNotBlank(query.getAreaId())) {
            querySql += String.format(" and c.areaId = '%s' ", query.getAreaId());
        }
        if (StringUtils.isNotBlank(query.getName())){
            querySql += String.format(" and c.name like concat('%s', '%s', '%s') ", "%", query.getName(), "%");
        }
        querySql+=" and c.deleted = false group by c.id ) a";
        List objectArrayList = sqlSingleList(querySql);
        return Long.valueOf(objectArrayList.get(0).toString());
    }

    @Override
    public List<String> findStaffIdsByChildId(String childrenId) {
        String querySql = String.format("select DISTINCT(rct.staffId) from rel_classes_children as rcc inner join rel_classes_teacher as rct on rcc.classesId=rct.classesId where rcc.childrenId='%s'",childrenId);
        return sqlSingleList(querySql);
    }
}
